package com.macro.mall.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.util.AliOssUtil;
import com.macro.mall.dto.BucketPolicyConfigDto;
import com.macro.mall.dto.MinioUploadDto;
import io.minio.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import static com.google.common.io.Files.getFileExtension;

/**
 * MinIO对象存储管理Controller
 *
 */
@Controller
@Api(tags = "AliOssController")
@Tag(name = "AliOssController", description = "阿里云对象存储管理")
@RequestMapping("/minio")
@RequiredArgsConstructor
public class AliOssController {

    private final AliOssUtil aliOssUtil;


    @ApiOperation("文件上传")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult upload(@RequestPart("file") MultipartFile file) {
        MinioUploadDto result = new MinioUploadDto();
        result.setName(file.getOriginalFilename());
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            String extention=originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectname = UUID.randomUUID().toString()+extention;
            String filePath=aliOssUtil.upload(file.getBytes(), objectname);
            result.setUrl(filePath);
            return CommonResult.success(result);
        } catch (IOException e) {
            return CommonResult.failed("文件上传失败!");
        }

    }
}
